import logging
import os
import urllib
import pickle
import httplib2

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp.util import login_required

from django import newforms as forms
#from django import forms
from django.utils import simplejson

from oauth2client.appengine import CredentialsProperty
from oauth2client.appengine import StorageByKeyName
from oauth2client.client import OAuth2WebServerFlow
from apiclient.discovery import build

import models
from main import BaseHandler
import gslite

class AdminPage(BaseHandler):
    """Renders the admin page"""
    @login_required
    def get(self):
        conf = models.ConfigModel.get_by_key_name('config')
        credentials = conf.credentials
        try:
            #warning, don't use project_id header for list bucket operations
            # cf http://code.google.com/p/gsutil/source/diff?spec=svn110&r=110&format=side&path=/trunk/src/gslib/project_id.py
            storage = gslite.GsClient(oauth=credentials.access_token)
            result = storage.get_bucket(conf.bucket_name)
            logging.info(result)
        except:
            logging.exception("could no access storage")
        self.render("admin.html", model=conf)
        
    def post(self):
        conf = models.ConfigModel(key_name='config')
        conf.client_id = self.request.get('CLIENT_ID')
        conf.client_secret = self.request.get('CLIENT_SECRET')
        conf.storage_project_id = self.request.get('STORAGE_PROJECT_ID')
        conf.bucket_name = self.request.get('BUCKET_NAME')
        conf.put()
        conf.credentials = StorageByKeyName(models.ConfigModel, 'config', 'credentials').get()
        if conf.credentials:
            self.redirect("/admin/config")
        else:
            flow = OAuth2WebServerFlow(
                # Visit https://code.google.com/apis/console to
                # generate your client_id, client_secret and to
                # register your redirect_uri.
                client_id=conf.client_id,
                client_secret=conf.client_secret,
                scope='https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/prediction',
                user_agent='gae-tweeter-sentiment-analysis-sample/1.0',
                domain='anonymous')
            callback = self.request.relative_url('/admin/oauth2callback')
            authorize_url = flow.step1_get_authorize_url(callback)
            memcache.set('config', pickle.dumps(flow))
            self.redirect(authorize_url)

class OAuth2ResetHandler(BaseHandler):
    """Resets OAuth Credentials"""
    @login_required
    def get(self):
        conf = models.ConfigModel.get_by_key_name('config')
        flow = OAuth2WebServerFlow(
            # Visit https://code.google.com/apis/console to
            # generate your client_id, client_secret and to
            # register your redirect_uri.
            client_id=conf.client_id,
            client_secret=conf.client_secret,
            scope='https://www.googleapis.com/auth/devstorage.full_control https://www.googleapis.com/auth/prediction',
            user_agent='gae-tweeter-sentiment-analysis-sample/1.0',
            domain='anonymous')
        callback = self.request.relative_url('/admin/oauth2callback')
        authorize_url = flow.step1_get_authorize_url(callback)
        memcache.set('config', pickle.dumps(flow))
        self.redirect(authorize_url)
            
class OAuth2CallbackHandler(BaseHandler):
  """OAuth Callback handler: store the OAuth Credentials"""
  @login_required
  def get(self):
    flow = pickle.loads(memcache.get('config'))
    if flow:
      credentials = flow.step2_exchange(self.request.params)
      StorageByKeyName(models.ConfigModel, 'config', 'credentials').put(credentials)
      self.redirect("/admin/config")
    else:
      pass
            
ROUTES = [
   ('/admin/config', AdminPage),
   ('/admin/oauth2callback', OAuth2CallbackHandler),   
   ('/admin/oauth', OAuth2ResetHandler),   
]

application = webapp.WSGIApplication(ROUTES, debug=True)

def main():
    util.run_wsgi_app(application)

if __name__ == "__main__":
    main()
